//
//  JYHomeController.m
//  JYShop
//
//  Created by 花花 on 2017/9/28.
//  Copyright © 2017年 花花. All rights reserved.
//

#import "JYHomeController.h"
#import "JYSearchBar.h"
#import "JYSearchViewController.h"
#import "JYHeaderView.h"
#import "JYFunView.h"
#import "JYFunModel.h"
#import <MJRefresh/MJRefresh.h>
#import "JYPublicCell.h"
#import "JYHomeLeftCell.h"
#import "JYHomeViewModel.h"
#import "JYHomeBannerModel.h"
#import "BaseWebViewController.h"
#import "JYCategorysModel.h"
#import "BaseModel.h"
#import "JYHomeTableViewProxy.h"
#import "PurchaseCarAnimationTool.h"
#import "JYShoppingCartManager.h"
#import "JYEmptyView.h"
@interface JYHomeController ()<UITableViewDataSource,UITableViewDelegate,SDCycleScrollViewDelegate,JYHomeViewModelDelegate>

@property(nonatomic) JYSearchBar *searchBar; //搜索

@property(nonatomic) JYHomeViewModel *viewModel; //数据请求

@property (nonatomic, strong)JYHeaderView *header; //banner

@property (nonatomic, strong) JYFunView *funView; //功能funView 10个

@property(nonatomic,strong)JYHomeTableViewProxy *homeRightTableViewProxy; //单独处理右边逻辑

@property (nonatomic) UITableView *leftTableView; //左边tableView

@property (nonatomic, strong) UITableView *scrollView; //控制contentSize

@property(nonatomic,strong)NSArray *leftArr; //tableView左边数据

@property(nonatomic,strong)UILabel *nameLabel; //商家名称

@property(nonatomic,strong)NSMutableArray  *bannerArr; //轮播图数据

@property(nonatomic,strong)NSMutableArray  *categorysArr; //fun数据 即collectionView数据


@property(nonatomic,assign)NSInteger totalCount;

@property(nonatomic,strong)NSMutableArray  *goodsListArr;//右边的数据

@property(nonatomic,copy)NSString  *selectedId;//


@end

@implementation JYHomeController

- (NSMutableArray *)goodsListArr{

    if (!_goodsListArr) {
        _goodsListArr = [NSMutableArray array];
    }
    return _goodsListArr;

}
#pragma mark - Life Cycle
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
       [self.navigationController setNavigationBarHidden:YES animated:NO];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:NO];
}
- (void)refreshRightList{

//    [self.viewModel requsetHomeRithtTableList:self.goodsListArr];
    
       [self requestGoodsWithCategoryId:_selectedId];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(refreshRightList) name:kHomeCountChangeNotification object:nil];
    
    [self setupSubView];
    [self loadDataFromNetwork];
    
    
    [self GoodCarTotalCountFormNetwork];

    
      NSLog(@"model ===%@ +++++++%@",LH.userId,LH.userInfor.merchantName);
      self.automaticallyAdjustsScrollViewInsets = NO;
  
    [self setupRefresh];
  
}

- (void)setupRefresh{


    [self setupRefreshTarget:self.tableView With:HHRefreshTypeHeaderAndFooter];
}
//
- (void)loadgoodsListWithpageNo:(int)pageNo andStatus:(int)status categoryId:(NSString *)categoryId{

    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"pageSize"] = @(10);
    param[@"pageNo"] = @(1);
    param[@"userId"] = LH.userId;
    param[@"categoryId"] = categoryId;
    JYWeakSelf;
    [HTTPRequest POST:kFrontGoodsUrl parameter:param success:^(id resposeObject) {
       
        if (SUCCESS) {
            
            [self.goodsListArr removeAllObjects];
            
            self.goodsListArr = [BaseModel mj_objectArrayWithKeyValuesArray:resposeObject[@"data"][@"list"]];
            
          
            for (NSDictionary *dic in resposeObject[@"data"][@"list"]) {
                
                
                
                self.viewModel.depositObjDic = dic[@"depositObj"];
                
            }
           
            [self.viewModel requsetHomeRithtTableList:self.goodsListArr];
            
            [self.tableView reloadData];
            int totalPage = [resposeObject[@"data"][@"total"] intValue];
            
            [weakSelf successEndRefreshStatus:status totalPage:totalPage];
        }else{
            
              [weakSelf failEndRefreshStatus:status];
            
            [MBProgressHUD LY_ShowError:resposeObject[@"msg"] time:2.0];
            
        }
        
        self.currentPageStatus = PageStatusSucceed;
        
        NSLog(@"_____右边数据右边数据______%@",resposeObject);
        
    } failure:^(NSError *error) {
        
        [MBProgressHUD LY_ShowError:kNoNetworkTips time:2.0];
      
    }];
    
}
- (void)pullUpRefresh:(int)page lastPage:(BOOL)isLastPage{

    if (isLastPage) return;
    
    [self loadgoodsListWithpageNo:page andStatus:1 categoryId:nil];
    
}
- (void)pullDownRefresh:(int)page{

    [self loadgoodsListWithpageNo:page andStatus:0 categoryId:nil];

}
- (void)requestGoodsWithCategoryId:(NSString *)categoryId{
    
    NSLog(@"categoryIdcategoryId:%@",categoryId);
    [self loadgoodsListWithpageNo:1 andStatus:-1 categoryId:categoryId];
}


#pragma mark - loadData
- (void)loadDataFromNetwork{

    //轮播图
    [self.viewModel handlerBannerDataWithAreaId:@"d9a89941231d49b790bc2de8eb02e20f" Success:^(NSArray *lbtArr) {
       
        [self.bannerArr removeAllObjects];
        
        for (int i = 0; i<lbtArr.count; i++){
            JYHomeBannerModel *model = lbtArr[i];
            [self.bannerArr addObject:model.image];
        }
        self.header.imageURLStringsGroup = self.bannerArr;
        self.header.placeholderImage = [UIImage imageNamed:@"home_banner"];
        [self.scrollView reloadData];
        
    }];
    
    //fun数据包括左边数据
    [self.viewModel  handlerCategoryDataWithSuccess:^(NSArray *categorysArr) {
       
        for (NSDictionary *dic in categorysArr) {
       
            JYCategorysModel *model = [JYCategorysModel mj_objectWithKeyValues:dic];
            [self.categorysArr addObject:model];
        }
        
        self.funView.dataArr = self.categorysArr;
        
    }];

}

#pragma mark - setupSubView
- (void)setupSubView{
    
    [self.view addSubview:self.scrollView ];
    [self.scrollView addSubview:self.funView];
    [self.scrollView addSubview:self.leftTableView];
    [self.scrollView addSubview:self.tableView];

    [self setupTableView];
    
    JYWeakSelf;
    _searchBar = [[JYSearchBar alloc]initWithOffSet:125 ];
    _searchBar.searchBarClickCallBack = ^{
        JYSearchViewController *searchVc = [JYSearchViewController new];

        [weakSelf.navigationController pushViewController:searchVc animated:YES];
    };
    [self.view addSubview:_searchBar];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.left.mas_equalTo(leftTableWidth+1);
        make.top.mas_equalTo(bannerHight+funHight+10);
        make.width.mas_equalTo(rightTableWidth-2);
        make.height.mas_equalTo(tableViewHeight);
        
    }];
    [_searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view.mas_left);
        make.right.equalTo(weakSelf.view.mas_right);
        make.top.equalTo(weakSelf.view.mas_top);
        make.height.equalTo(@64);
    }];
    
    [self.searchBar addSubview:self.nameLabel];
    
}
- (void)setupTableView{

    self.tableView.rowHeight = 100;
    [self.tableView registerNib:[UINib nibWithNibName:@"JYPublicCell" bundle:nil] forCellReuseIdentifier:@"RightCellID"];
    self.tableView.decelerationRate = UIScrollViewDecelerationRateFast;
    self.tableView.decelerationRate = 0.1;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.dataSource = self.homeRightTableViewProxy;
    self.tableView.tableFooterView = [UIView new];
    self.tableView.showsVerticalScrollIndicator = NO;
    
}
#pragma mark - <JYHomeViewModelDelegate>
- (void)homeRightTableRequestDataSuccessWithArray:(NSMutableArray *)dataArray{
    
    self.homeRightTableViewProxy.dataArray = dataArray;
    
    [self.tableView reloadData];

}
- (void)shopcartAccountFortotalCount:(double)totalCount{
    
    [self.tableView reloadData];
}
#pragma mark - <UITableViewDelegate && UITableViewDataSource>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

      return self.leftArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    JYHomeLeftCell *cell = [tableView dequeueReusableCellWithIdentifier:@"leftCellID"];

    cell.model = [ self.leftArr safeObjectAtIndex:indexPath.row];
    return cell;

}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    NSLog(@"%f",scrollView.contentOffset.y);
    if (scrollView == self.scrollView) {
        
        _searchBar.progress = scrollView.contentOffset.y/64;
        CGFloat contentOffsetY = scrollView.contentOffset.y;
        if (contentOffsetY >= bannerHight-44) {
            
            [UIView animateWithDuration:0.2 animations:^{
                self.scrollView.contentOffset = CGPointMake(0, bannerHight-44);
            }];
        }
    }
    if ([scrollView isKindOfClass:[UITableView class]]) {
        
        CGFloat contentOffsetY = scrollView.contentOffset.y;
        
        if (contentOffsetY <= 0) {
            [UIView animateWithDuration:0.5 animations:^{
                
                self.scrollView.contentOffset = CGPointMake(0, 0);
            }];
        } else {
            
            [UIView animateWithDuration:0.5 animations:^{
                self.scrollView.contentOffset = CGPointMake(0, bannerHight-44);
                
            }];
        }
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == _leftTableView) {
        
        for (JYChildrenListMoel *model in self.leftArr) {
            model.selectedFlag = NO;
        }
        if (self.leftArr.count <= 0) return;
        JYChildrenListMoel *childernModel = [self.leftArr safeObjectAtIndex:indexPath.row];
        
        childernModel.selectedFlag = YES;
        
        [self requestGoodsWithCategoryId:childernModel.ID];
        
        [tableView reloadData];
    }

}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    
}

#pragma mark - SDCycleScrollViewDelegate
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
//    
//    NSString *jumpURLStr = [self.bannerArr[index] jumpUrl];
//    if ([jumpURLStr hasPrefix:@"#"]) return;
//    BaseWebViewController *webView =[[BaseWebViewController alloc]init];
//    [webView loadHttpRequestWithUrl:jumpURLStr];
//    [self.navigationController pushViewController:webView animated:YES];
    
}
#pragma mark - Setter && Getter Methods
- (JYHomeTableViewProxy *)homeRightTableViewProxy {
    if (_homeRightTableViewProxy == nil){
        JYWeakSelf;
        _homeRightTableViewProxy = [[JYHomeTableViewProxy alloc] init];
        _homeRightTableViewProxy.ShopHandlerSelectBlock =  ^(BOOL isSelected,NSIndexPath *indexPath){ //
        
            if (isSelected == YES) { //收藏
              [weakSelf.viewModel selectProductAtIndexPath:indexPath isSelected:isSelected];
                
            }else{//取消收藏
                [weakSelf.viewModel cancelProductAtIndexPath:indexPath];
            }
        };
        _homeRightTableViewProxy.ShopCartHandlerChangeCountBlock = ^(NSInteger count, NSIndexPath *indexPath){ //数量的变化
            
         [weakSelf.viewModel changeCountAtIndexPath:indexPath count:count];
        };
        
        _homeRightTableViewProxy.joinShopCarAninationBlock = ^(UIImageView *imageView, NSIndexPath *indexPath){
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
               
                UIView *tabbarBtn = weakSelf.tabBarController.tabBar.subviews[3];
                [PurchaseCarAnimationTool shakeAnimation:tabbarBtn];
                
                [weakSelf GoodCarTotalCountFormNetwork];
            });
        };
        
    }
    return _homeRightTableViewProxy;
}
- (void)GoodCarTotalCountFormNetwork{

    [HTTPRequest POST:kUserShoppingTrolleyGoodsTotalUrl parameter:@{@"userId":LH.userId} success:^(id resposeObject) {
        JYWeakSelf;
        if (SUCCESS) {
            int totalCount = [resposeObject[@"data"] intValue];
            
            NSLog(@"购物车数量: %d",totalCount);
            if (totalCount>0) {
                weakSelf.tabBarController.childViewControllers[2].tabBarItem.badgeValue = [NSString stringWithFormat:@"%d",totalCount];
                
            }else{
                
                weakSelf.tabBarController.childViewControllers[2].tabBarItem.badgeValue = nil;
            }
        }else{
            
            [MBProgressHUD LY_ShowError:resposeObject[@"msg"] time:2.0];
        }
        
    } failure:^(NSError *error) {
        
    }];
}
- (UITableView *)leftTableView{
    
    if (!_leftTableView) {
        _leftTableView = [self setTableViewFrame:CGRectMake(0, CGRectGetMaxY(self.funView.frame)+10, leftTableWidth,tableViewHeight) rowHeight:kTableView_rowHeight NibName:@"JYHomeLeftCell" Identifier:@"leftCellID"];
        _leftTableView.bounces = NO;
        _leftTableView.delegate = self;
        _leftTableView.dataSource = self;
        _leftTableView.decelerationRate = UIScrollViewDecelerationRateFast;
        _leftTableView.decelerationRate = 0.1;
        _leftTableView.showsVerticalScrollIndicator = NO;
        _leftTableView.tableFooterView = [UIView new];
    }
    return _leftTableView;
}

- (UITableView *)setTableViewFrame:(CGRect)frame rowHeight:(CGFloat)rowHeight NibName:(NSString *)nibName Identifier:(NSString *)Identifier{

    UITableView *tableView =  [[UITableView alloc] initWithFrame:frame];
    tableView.rowHeight = rowHeight;
    [tableView registerNib:[UINib nibWithNibName:nibName bundle:nil] forCellReuseIdentifier:Identifier];
    return tableView;
}

- (UIScrollView *)scrollView{
    
    if (!_scrollView) {
        _scrollView = [[UITableView alloc]initWithFrame:CGRectMake(0, 20, Screen_Width, Screen_Height-49-20)];
        _scrollView.delegate = self;
        _scrollView.tableHeaderView = self.header;
        _scrollView.tableFooterView =[UIView new];
        _scrollView.backgroundColor = kBgColor;
        _scrollView.bounces = NO;
        _scrollView.contentSize = CGSizeMake(Screen_Width, scrollViewContentHeight);
    }
    return _scrollView;
}
- (JYHeaderView *)header{
    
    if (!_header) {
        _header =  [JYHeaderView headerView:(CGRect){0, 0, Screen_Width, bannerHight}];
        _header.delegate = self;
    }
    return _header;
    
}
- (JYFunView *)funView{
    
    if (!_funView) {

        _funView = [[JYFunView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.header.frame), Screen_Width, funHight)];
        JYWeakSelf;
        _funView.FunDidSelectItemAtIndexPath = ^(NSArray *leftArr){
      
            weakSelf.leftArr = [JYChildrenListMoel mj_objectArrayWithKeyValuesArray:leftArr];
            
            [weakSelf.viewModel SelectedProducts:[[weakSelf.leftArr firstObject] ID]];
            
            [weakSelf tableView:weakSelf.leftTableView didSelectRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]];
            
            [weakSelf.leftTableView reloadData];
        };
    }
    return _funView;
}
- (UILabel *)nameLabel{
    
    if (!_nameLabel) {
        _nameLabel = [UILabel labelText:[[NSUserDefaults standardUserDefaults] objectForKey:kMerchantName] fontSize:14 textColor:k3Color textAlignment:NSTextAlignmentCenter];
        _nameLabel.layer.cornerRadius = 18;
        _nameLabel.layer.masksToBounds = YES;
        _nameLabel.frame =CGRectMake(10, 25, 100, 32);
        _nameLabel.backgroundColor = [UIColor colorWithHexString:@"999999" alpha:.5];
    }
    return _nameLabel;
}
- (JYHomeViewModel *)viewModel{
    if (!_viewModel) {
        _viewModel =[[JYHomeViewModel alloc]init];
        _viewModel.delegate = self;
    }
    return _viewModel;
}
- (NSMutableArray *)bannerArr{

    if (!_bannerArr) {
        _bannerArr = [NSMutableArray array];
    }
    return _bannerArr;
}
- (NSArray *)leftArr{

    if (!_leftArr) {
        _leftArr = [NSArray array];
    }
    return _leftArr;
}
- (NSMutableArray *)categorysArr{
    if (!_categorysArr) {
        _categorysArr =[NSMutableArray array];
    }
    return _categorysArr;

}
- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    
}
@end
